<template>
  <div class="main">
    <!-- 搜索数据 -->
    <div class="seach">
      <el-input v-model="obj.query" placeholder="输入用户名" />
      <el-button type="success" plain @click="seachUser">搜索</el-button>
      <el-button type="success" plain @click="addUserBox = true">添加用户</el-button>
      <el-button type="success" plain @click="downloadExcel">导出excel</el-button>
          <!-- 分页器 -->
    <el-pagination
      v-model:current-page="obj.pagenum"
      v-model:page-size="obj.pagesize"
      :page-sizes="[1, 3, 6, 12]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="obj.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    </div>

    <!-- 数据表格 -->
    <el-table :data="sdata.list" style="width: 100%" >
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="手机号" prop="mobile" />
      <el-table-column label="邮箱" prop="email" />
      <el-table-column label="创建时间" prop="create_time">
        <template #default="scope">
          {{ timestampToTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="是否禁用">
        <template #default="scope">
          <el-switch
            v-model="scope.row.mg_state"
            inline-prompt
            active-text="是"
            inactive-text="否"
            @click="edit(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="role_name" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" :icon="Edit" plain @click="editUserInfo(scope.row)" />
          </el-tooltip>
          <el-tooltip content="角色修改" placement="top">
            <el-button type="success" :icon="Setting" plain @click="editRolesInfo(scope.row)" />
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button type="danger" :icon="Delete" plain @click="deleteUser(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加用户弹窗 -->
    <el-dialog v-model="addUserBox" title="添加用户" width="30%" :before-close="addBoxClose">
      <el-form ref="formRef" :model="userInfo" label-width="100px" class="demo-ruleForm">
        <el-form-item
          label="用户名"
          prop="username"
          :rules="[{ required: true, message: '用户名必填' }]"
        >
          <el-input v-model.trim="userInfo.username" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          :rules="[{ required: true, message: '密码必填' }]"
        >
          <el-input v-model.trim="userInfo.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userInfo.email" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.number="userInfo.mobile" type="text" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addUserBox = false">取消</el-button>
          <el-button type="primary" @click="addUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="editBox" title="编辑用户信息" width="30%" :before-close="editBoxClose">
      <el-form ref="formRef" :model="editUser" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <template #default="scope">
            <!-- <div>{{ scope.row }}</div> -->
            <el-input v-model="editUser.username" type="text" disabled="disabled" />
          </template>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editUser.email" type="text" autocomplete="off" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model.number="editUser.mobile" type="text" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editBox = false">取消</el-button>
          <el-button type="primary" @click="editSuccess"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色的弹窗 -->
    <el-dialog v-model="editRoles" title="修改角色" width="30%" :before-close="editRolesClose">
      <el-form ref="formRef" :model="editUser" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <template #default="scope">
            <el-input v-model="rolesInfo.username" type="text" disabled="disabled" />
          </template>
        </el-form-item>
        <el-form-item label="角色名称">
          <el-select v-model="rolesInfo.roleId">
            <el-option v-for="item in rolesList" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editRoles = false">取消</el-button>
          <el-button type="primary" @click="editRolesSuccess"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getUserListApi,
  addUserInfoApi,
  editStatusApi,
  editUserInfoApi,
  editSuccessApi,
  deleteUserApi,
  getRolesListApi,
  editRolesApi
} from '@/api/userList'
// 引入图标
import { Delete, Edit, Setting } from '@element-plus/icons-vue'
// 引入excel导=模块
import {downloadExcel} from '@/utils/fileExport'
const sdata = reactive({
  list: []
})
// 接收用户数据
const obj = reactive({
  pagenum: 1, //请求的页码
  pagesize: 12, //请求的条数
  total: 0, //数据总条数
  query: '' //查询条件
})
// 发起请求,获取数据列表
const getList = () => {
  getUserListApi(obj)
    .then((res) => {
      // console.log(res)
      sdata.list = res.data.users
      // console.log(sdata.list);
      // 页数
      obj.pagenum = res.data.pagenum
      // 总条数
      obj.total = res.data.total
    })
    .catch((error) => {
      console.log(error)
    })
}
onMounted(() => {
  getList()
})

const handleSizeChange = (val) => {
  // 每页几条数据
  console.log(`${val} items per page`)
  obj.pagesize = val
  getList()
}
const handleCurrentChange = (val) => {
  // 第几页数据
  console.log(`current page: ${val}`)
  obj.pagenum = val
  getList()
}
// 时间戳转换函数
const timestampToTime=(timestamp)=> {
  if (timestamp === 0 || timestamp == null) {
    return ''
  } else {
    var date = new Date(timestamp * 1000)
    var Y = date.getFullYear() + '-'
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    return Y + M + D
  }
}
// 搜索用户
const seachUser = () => {
  getList()
}

//控制添加用户编辑框是否弹出
const addUserBox = ref(false)
// 关闭添加弹窗
const addBoxClose = (done) => {
  done()
}
// 接收添加表单用户信息
const userInfo = reactive({
  username: '',
  password: '',
  email: '',
  mobile: ''
})
// 发起请求,添加用户
const addUser = async () => {
  addUserBox.value = false
  // console.log(userInfo);
  const res = await addUserInfoApi(userInfo)
  for (let key in userInfo) {
    userInfo[key] = ''
  }
  getList()
}

// 编辑用户状态
const edit = (data) => {
  editStatusApi(data)
}
// 编辑表单的数据
const editUser = reactive({
  id: '',
  username: '',
  email: '',
  mobile: ''
})
// 控制编辑用户编辑框是否弹出
const editBox = ref(false)
// 点击编辑按钮,发送请求,获取相关的用户信息
const editUserInfo = async (data) => {
  const res = await editUserInfoApi({ data })
  console.log('查询', res.data)
  for (let key in editUser) {
    editUser[key] = res.data[key]
  }
  editUser.username = res.data.username
  editUser.id = res.data.id
  editBox.value = true
}
// 控制编辑用户编辑框关闭
const editBoxClose = (done) => {
  done()
}
// 点击编辑的确定按钮,发送请求,编辑用户信息
const editSuccess = async () => {
  const res = await editSuccessApi(editUser)
  console.log(res)
  if (res.meta.status == 200) {
    editBox.value = false
    getList()
  }
}

// 点击删除按钮
const deleteUser = async (data) => {
  console.log(data.id)
  await ElMessageBox.confirm('你确定要删除该用户吗', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await deleteUserApi(data)
      console.log(res)
      if (res.meta.status == 200) {
        ElMessage({
          type: 'success',
          message: '已删除'
        })
        getList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

//控制修改角色的弹窗弹出
const editRoles = ref(false)
// 控制修改角色框关闭
const editRolesClose = (done) => {
  done()
}
const rolesList = ref([])
const rolesInfo=reactive({
    username:'',
    roleName:'',
    userId:'',
    roleId:''
})
// 点击编辑,发起请求
const editRolesInfo = async (data) => {
  // console.log(data);
  // 弹窗中的信息赋值
  rolesInfo.username = data.username
  rolesInfo.roleName = data.role_name

  const res =await editUserInfoApi({data})

  rolesInfo.userId = res.data.id
  rolesInfo.roleId=res.data.rid
  const resRoles = await getRolesListApi()
  // console.log('请求返回的角色数据',resRoles);
  // 拿到角色列表
  rolesList.value =resRoles.data.map(item=>({roleName: item.roleName, roleId: item.id}));
  editRoles.value = true
}
// 点击确定发起修改角色请求
const editRolesSuccess = async()=>{
  const res = await editRolesApi({id:rolesInfo.userId,rid:rolesInfo.roleId})
  // console.log(res);
  getList()
  editRoles.value = false
}

// // 映射的数据
// const transData=(rows)=>{
//     const map=reactive({
//     id:'序号',
//     email:'邮箱',
//     create_time:'创建时间',
//     mg_state:'是否禁用',
//     role_name:'角色名称',
//     username:'用户名称'
//     })

//     // 表头键名
//     const headerKeys = Object.keys(rows[0])

//     // 表头
//     const header = headerKeys.map(item=>{
//       return map[item]
//     })
//     // timestampToTime//转换时间的方法,需要传参
//     const data = rows.map((obj,index)=>{
//       // console.log(obj.create_time);//创建时间
//       obj.create_time=  timestampToTime(obj.create_time)
//       // console.log(obj.create_time);//创建时间
//       obj.id=(index+1)
//       return Object.values(obj)
//     })

//     return {header,data}
// }
// // 点击按钮,导出文件
// const downloadExcel=async ()=>{
//   // 发起请求,拿到最新数据
//   const res = await  getUserListApi(obj)
//   const excelObj = transData(res.data.users)
//   // console.log(excelObj);
//     const toExcel = new JsExportExcel({
//       fileName:'info',//文件名
//       datas:[
//         {
//           sheetData:excelObj.data,
//           sheetName:'sheet',
//           sheerFilter:["tow","one"],
//           sheetHeader:excelObj.header,//表头 必填
//           autoWidth: true,
//           // columnWidths:[20,20],
//         }
//       ]

//     })
//     toExcel.saveExcel()
// }
</script>

<style scoped lang="scss">
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.el-pagination{
  margin-left: 180px;
}
.seach {
  display: flex;
  background-color: antiquewhite;
  padding: 20px;
  margin: 0 auto;
  .el-input {
    width: 200px;
  }
}
.el-table{
  overflow-y: auto;
}
</style>
